# vim: fdm=marker fmr={{{,}}} cms=#%s

import misc 
import errcode 

ITEM_DLM="\xff"
ITEM_SIZE_CHAR=5
ITEM_MAX_SIZE=((1<<ITEM_SIZE_CHAR * misc.BIT_OF_CHAR / 2) - 1)

def put_item(msg, *items):
#{{{
    total_size=0
    for item in items:
        if isinstance(item, int):
            item=str(item)
        size=len(item)
        if size > ITEM_MAX_SIZE:
            return None,-1
        msg+="%0*X"%(ITEM_SIZE_CHAR,size) + ITEM_DLM + item + ITEM_DLM
        total_size+=ITEM_SIZE_CHAR+1+size+1
    return msg,total_size
#}}}

def get_item(msg, curr):
#{{{
    left_size=len(msg)-curr
    if left_size < ITEM_SIZE_CHAR+1+1:
        return None,curr
    item_pos=curr+ITEM_SIZE_CHAR+1
    if msg[item_pos-1] != ITEM_DLM:
        return None,curr
    item_size=int(msg[curr:curr+ITEM_SIZE_CHAR], base=16)
    if item_size < 0 or item_size > left_size-ITEM_SIZE_CHAR-1-1 or msg[item_pos+item_size] != ITEM_DLM:
        return None,curr
    item=msg[item_pos:item_pos+item_size]
    curr+=ITEM_SIZE_CHAR+1+item_size+1
    return item,curr
#}}}
